<script lang="ts" setup>
import type { SysMenu } from '#/api/platform/sysmenu';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { addMenu, editMenu } from '#/api/platform/sysmenu';
import { $t } from '#/locales';

import { formSchema } from '../data';

const emit = defineEmits(['success']);

const [Form, formApi] = useVbenForm({
  layout: 'horizontal',
  schema: formSchema(),
  commonConfig: {
    formItemClass: 'col-span-2 md:col-span-1',
  },
  wrapperClass: 'grid-cols-2 gap-x-4',
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    const data = (await formApi.getValues()) as SysMenu;

    if (!data.parentId) {
      data.parentId = 0;
    }
    try {
      await (data?.menuId ? editMenu(data) : addMenu(data));
      modalApi.close();
      emit('success');
    } finally {
      modalApi.lock(false);
    }
  },
  onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    const data = modalApi.getData<SysMenu>();
    modalApi.setState({
      title: data.menuId
        ? $t('ui.actionTitle.edit', [$t('menu.menu')])
        : $t('ui.actionTitle.create', [$t('menu.menu')]),
    });
    if (data) {
      formApi.setValues(data, false);
    }
  },
});
</script>

<template>
  <Modal class="w-full max-w-[700px]">
    <Form class="mx-4" />
  </Modal>
</template>
